package service

import (
	"appointment-srv/basic/config"
	__ "appointment-srv/basic/proto"
	"appointment-srv/handler/models"
	"appointment-srv/utils"
	"context"
	"encoding/json"
	"fmt"
	"github.com/google/uuid"
	"gopkg.in/errgo.v2/fmt/errors"

	"log"
	"math/rand"
	"strconv"
	"time"
)

type Server struct {
	__.UnimplementedAppointmentServer
}

// SayHello implements helloworld.GreeterServer
func (s *Server) SayHello(_ context.Context, in *__.StreamReq) (*__.StreamResp, error) {
	log.Printf("Received: %v", in.GetName())
	return &__.StreamResp{}, nil
}
func (s *Server) GetUserInfo(_ context.Context, in *__.GetUserInfoReq) (*__.GetUserInfoResp, error) {

	var r models.User
	if err := r.GetUserMobile(config.DB, in.Phone); err != nil {
		return nil, err
	}
	if r.Phone == "" {
		return nil, fmt.Errorf("用户不存在")
	}
	if r.Password != in.Password {
		return nil, fmt.Errorf("密码错误")
	}
	if err := r.GetUserinfo(config.DB); err != nil {
		return nil, err
	}
	return &__.GetUserInfoResp{
		Id: int64(r.ID),
	}, nil
}
func (s *Server) SendSms(_ context.Context, in *__.SendSmsReq) (*__.SendSmsResp, error) {

	code := rand.Intn(9000) + 1000
	utils.SendSms(in.Phone, strconv.Itoa(code))
	config.Rdb.Set(config.Ctx, "sendSms"+in.Phone, code, time.Minute*5)
	return &__.SendSmsResp{
		Code: strconv.Itoa(code),
	}, nil
}
func (s *Server) HospitalList(_ context.Context, in *__.HospitalListReq) (*__.HospitalListResp, error) {
	var ho models.Hospital
	list, err := ho.GetList(config.DB, int(in.Page), int(in.PageSize))
	if err != nil {
		return nil, err
	}
	return &__.HospitalListResp{
		List: list,
	}, nil
}

func (s *Server) PhysicalList(_ context.Context, in *__.PhysicalListReq) (*__.PhysicalListResp, error) {
	var ho models.PhysicalExamPackage

	var department []*__.PhysicalList
	physical := fmt.Sprintf("departmentlist")
	res, _ := config.Rdb.Get(config.Ctx, physical).Result()
	if res != "" {
		json.Unmarshal([]byte(res), &department)
	} else {
		list, err := ho.GetList(config.DB)
		if err != nil {
			return nil, err
		}
		json.Marshal(&list)
		config.Rdb.Set(config.Ctx, physical, res, time.Minute*10)
	}

	return &__.PhysicalListResp{
		List: department,
	}, nil
}

func (s *Server) DepartmentList(_ context.Context, in *__.DepartmentListReq) (*__.DepartmentListResp, error) {
	var ho models.Department
	var department []*__.DepartmentList
	physical := fmt.Sprintf("departmentlist")
	res, _ := config.Rdb.Get(config.Ctx, physical).Result()
	if res != "" {
		json.Unmarshal([]byte(res), &department)
	} else {
		list, err := ho.GetList(config.DB)
		if err != nil {
			return nil, err
		}
		json.Marshal(&list)
		config.Rdb.Set(config.Ctx, physical, res, time.Hour*24)
	}

	list, err := ho.GetList(config.DB)
	if err != nil {
		return nil, err
	}
	return &__.DepartmentListResp{
		List: list,
	}, nil
}

func (s *Server) DepartmentAdd(_ context.Context, in *__.DepartmentAddReq) (*__.DepartmentAddResp, error) {
	var de models.Department
	de.Introduction = in.Introduction
	de.Department = in.Department
	de.HospitalId = int(in.HospitalId)
	de.CategoryId = int(in.CategoryId)
	de.Status = int(in.Status)
	if err := de.CreateDepartment(config.DB); err != nil {
		return nil, errors.New("添加失败了")
	}
	return &__.DepartmentAddResp{
		Id: int64(de.ID),
	}, nil
}

func (s *Server) OrderCreate(_ context.Context, in *__.OrderCreateReq) (*__.OrderCreateResp, error) {
	var eu models.User
	if err := eu.GetUserinfoById(config.DB, int(in.UserId)); err != nil {
		return nil, err
	}
	if eu.ID == 0 {
		return nil, errors.New("用户不存在")
	}
	var ho models.Shop
	if err := ho.GetShopById(config.DB, int(in.ShopId)); err != nil {
		return nil, fmt.Errorf("商品不存在")
	}
	if ho.ID == 0 {
		return nil, errors.New("商品不存在")
	}
	//amount := ho.Price * float64(in.Num)
	var od models.Order

	od.UserId = int(in.UserId)
	od.OrderSn = uuid.NewString()
	od.PaymentMethod = int(in.PaymentMethod)
	config.DB.Create(&od)
	ao := utils.Alipay(od.OrderSn, "200")
	return &__.OrderCreateResp{
		Id:  int64(od.ID),
		Url: ao,
	}, nil
}

func (s *Server) UserOrderList(_ context.Context, in *__.UserOrderListReq) (*__.UserOrderListResp, error) {
	var ho models.Order
	var se models.User
	if err := se.GetUserinfoById(config.DB, int(se.ID)); err != nil {
		return nil, err
	}
	if se.ID != uint(ho.UserId) {
		return nil, fmt.Errorf("用户订单只能是我自己的")
	}

	list, err := ho.GetList(config.DB, int(in.Page), int(in.Pagesize))
	if err != nil {
		return nil, err
	}
	return &__.UserOrderListResp{
		List: list,
	}, nil
}

func (s *Server) DoctorList(_ context.Context, in *__.DoctorListReq) (*__.DoctorListResp, error) {
	var ho models.Doctor
	list, err := ho.Getlists(config.DB)
	if err != nil {
		return nil, err
	}
	return &__.DoctorListResp{
		List: list,
	}, nil
}

func (s *Server) OrderUpdate(_ context.Context, in *__.OrderUpdateReq) (*__.OrderUpdateResp, error) {
	var ho models.Order
	if err := ho.Update(config.DB, int(in.UserId)); err != nil {
		return nil, err
	}
	config.Rdb.SetNX(config.Ctx, "lorderlist", ho.ID, time.Hour)
	if ho.Storck > 500 {
		return nil, fmt.Errorf("不能超过500库存数量")
	}
	return &__.OrderUpdateResp{
		Id: int64(ho.ID),
	}, nil
}

func (s *Server) DelOrder(_ context.Context, in *__.OrderDelReq) (*__.OrderDelResp, error) {
	var ho models.Order
	if err := ho.Del(config.DB, int(in.Id)); err != nil {
		return nil, err
	}

	return &__.OrderDelResp{
		Id: in.Id,
	}, nil
}

func (s *Server) DailyReserveStockAdd(_ context.Context, in *__.DailyReserveStockAddReq) (*__.DailyReserveStockAddResp, error) {
	var ho models.DailyReserveStock
	if err := ho.Create(config.DB); err != nil {
		return nil, err
	}
	return &__.DailyReserveStockAddResp{
		Id: in.PackageId,
	}, nil
}

func (s *Server) OnlineAdd(_ context.Context, in *__.OnlineAddReq) (*__.OnlineAddResp, error) {
	ho := models.Online_consult_desc{

		ConsultId:    int(in.ConsultId),
		UserId:       int(in.UserId),
		DoctorId:     int(in.DoctorId),
		DepartmentId: int(in.DepartmentId),
		Ontype:       int(in.Ontype),
		MainComplain: in.MainComplain,
		//IsUrgent:     in.IsUrgent,
		Status: int(in.Status),
	}
	if err := ho.Creat(config.DB); err != nil {
		return nil, err
	}
	return &__.OnlineAddResp{
		Id: int64(ho.ID),
	}, nil
}
